/*
   Copyright (c) 2020 LinkedIn Corp.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.linkedin.d2.balancer.servers;

import com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore;
import com.linkedin.d2.discovery.stores.zk.ZookeeperEphemeralPrefixGenerator;

/**
 * EphemeralPrefixGenerator helps to create a hash based prefix for Ephemeral Nodes in {@link ZooKeeperEphemeralStore}
 * The hash generated by EphemeralPrefixGenerator will be based on the URI of the {@link ZooKeeperAnnouncer}
 * This hash prefixing of EphemeralNodes helps {@link ZooKeeperEphemeralStore} to optimize the reads during markUp/markDown
 * @author Nizar Mankulangara (nmankulangara@linkedin.com)
 */

public class AnnouncerHostPrefixGenerator implements ZookeeperEphemeralPrefixGenerator
{
  private final String _hostName;

  public AnnouncerHostPrefixGenerator(String hostName)
  {
    if (hostName == null)
    {
      _hostName = null;
    }
    else
    {
      // Since just want to use the machine name for pre-fix and not the entire FQDN to reduce the size of name
      int machineNameEndIndex = hostName.indexOf('.');
      _hostName = machineNameEndIndex > 0 ? hostName.substring(0, machineNameEndIndex) : hostName;
    }
  }

  @Override
  public String generatePrefix()
  {
    return _hostName;
  }
}
